package com.lagou.rpc.common.converter;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * fastjson转换实现
 *
 * @author wlz
 * @date 2020/6/16
 */
public class FastJsonConverter implements Converter {

    private Charset unifyCharset = StandardCharsets.UTF_8;

    @Override
    public byte[] obj2Bytes(Object obj) {
        if (obj == null) {
            return null;
        }
        if (isSimpleType(obj.getClass())) {
            return simple2Bytes(obj);
        }
        String objStr = JSONObject.toJSONString(obj);
        return objStr.getBytes(unifyCharset);
    }

    @Override
    public Object bytes2Obj(byte[] content, int offset, int length, Type type) {
        String objStr = new String(content, offset, length, unifyCharset);
        if (isSimpleType(type)) {
            return string2SimpleData(objStr, type);
        }
        return JSONObject.parseObject(objStr, type);
    }

    private boolean isSimpleType(Type type) {
        return type == byte.class || type == Byte.class ||
                type == short.class || type == Type.class ||
                type == int.class || type == Integer.class ||
                type == long.class || type == Long.class ||
                type == float.class || type == Float.class ||
                type == double.class || type == Double.class ||
                type == boolean.class || type == Boolean.class ||
                type == char.class || type == Character.class ||
                type == String.class;
    }

    private byte[] simple2Bytes(Object obj) {
        return String.valueOf(obj).getBytes();
    }

    private Object string2SimpleData(String s, Type type) {
        if (byte.class == type || Byte.class == type) {
            return Byte.parseByte(s);
        }
        if (short.class == type || Short.class == type) {
            return Short.parseShort(s);
        }
        if (int.class == type || Integer.class == type) {
            return Integer.parseInt(s);
        }
        if (long.class == type || Long.class == type) {
            return Long.parseLong(s);
        }
        if (float.class == type || Float.class == type) {
            return Float.parseFloat(s);
        }
        if (double.class == type || Double.class == type) {
            return Double.parseDouble(s);
        }
        if (boolean.class == type || Boolean.class == type) {
            return Boolean.parseBoolean(s);
        }
        if (char.class == type || Character.class == type) {
            return s.charAt(0);
        }
        return s;
    }

}
